<?php declare(strict_types=1);
/**
 * @author      xianganyall <xianganyall@gmail.com>
 * @copyright   2023-2025 owner
 **/

namespace Srv\Libs\Pools;

use Srv\Libs\Common\CommTime;

final class PoolItem
{
    private ?object $poolObject         = null;         // 池对象
    private int $poolObjectId           = 0;            // 池对象Id
    private int $createTime             = 0;            // 池对象创建时间[秒]
    private int $lastCheckTime          = 0;            // 池对象最后检查时间[秒]
    private int $lastUseTime            = 0;            // 池对象最后使用时间[秒]
    private bool $isUse                 = false;        // 池对象是否使用中

    /**
     * PoolItem constructor.
     * @param object $poolObject
     * @param int $poolObjectId
     * __construct
     */
    final public function __construct(object $poolObject, int $poolObjectId = 0)
    {
        $this->poolObject               = $poolObject;
        $this->poolObjectId             = $poolObjectId;
        $this->createTime               = CommTime::getTimeStamp(0);
    }

    /**
     * @return object
     * getPoolObject
     */
    final public function getPoolObject():object
    {
        return $this->poolObject;
    }

    /**
     * @return int
     * getPoolObjectId
     */
    final public function getPoolObjectId():int
    {
        return $this->poolObjectId;
    }

    /**
     * @return bool
     * isUse
     */
    final public function isUse():bool
    {
        return $this->isUse;
    }

    /**
     * freed
     */
    final public function freed():void
    {
        $this->isUse            = false;
    }

    /**
     * @return bool
     * used
     */
    final public function used():bool
    {
        if($this->isUse) return true;
        $this->isUse            = true;
        $this->lastUseTime      = CommTime::getTimeStamp(0);
        return true;
    }

    /**
     * updateCheckTime
     */
    final public function updateCheckTime():void
    {
        $this->lastCheckTime    = CommTime::getTimeStamp(0);
    }

    /**
     * @param int $checkTime
     * @return bool
     * isCheck
     */
    final public function isCheck(int $checkTime):bool
    {
        if($checkTime <= 0) return false;
        if($this->isUse()) return false;
        $currTime       = CommTime::getTimeStamp(0);
        if($this->lastCheckTime > 0){
            return $currTime >= $this->lastCheckTime + $checkTime;
        }
        return $currTime >= $this->createTime + $checkTime;
    }

    /**
     * @param int $recycleTime
     * @return bool
     * isRecycle
     */
    final public function isRecycle(int $recycleTime):bool
    {
        if($this->isUse()) return false;
        $currTime       = CommTime::getTimeStamp(0);
        if($this->lastUseTime > 0){
            return $currTime >= $this->lastUseTime + $recycleTime;
        }
        return $currTime >= $this->createTime + $recycleTime;
    }
}